package com.oazon.system;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;

import com.oazon.moco.link.core.LinkSDK;
import com.oazon.moco.link.core.source.LinkEventSource;

public class WifiService extends Service {

	private boolean isRunning = false;
	private boolean curWifiStatus = true;
	private Thread wifiStatuThread = null;

	private NetworkInfo getNetworkInfo() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		return networkInfo;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		start();
		return null;
	}

	@Override
	public void onDestroy() {
		stop();
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	class WifiStatuRunnable implements Runnable {

		@Override
		public void run() {
			while (isRunning) {

				boolean wifiStatu = getNetworkInfo().isConnected();

				if (curWifiStatus != wifiStatu) {
					Log.d("gavin", "wifi状态改变成:" + wifiStatu);

					WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
					WifiInfo wifiInfo = wifiManager.getConnectionInfo();
					String ssid = wifiInfo.getSSID();
					//将消息发送出去
					LinkSDK.getInstance().wifiConnected(new LinkEventSource(),
							wifiStatu, ssid);
					curWifiStatus = wifiStatu;
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void start() {

		if (!isRunning) {
			isRunning = true;

			if (wifiStatuThread == null) {
				wifiStatuThread = new Thread(new WifiStatuRunnable());
				wifiStatuThread.start();
			}
		}
	}

	private void stop() {

		if (isRunning) {
			isRunning = false;

			if (wifiStatuThread != null) {
				try {
					wifiStatuThread.join(100);
					wifiStatuThread.interrupt();
					wifiStatuThread = null;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
